<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span='12'>
            <a-form-item label='项目简称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['projectName',validatorRules.projectShortName]"
                :trigger-change='true'
                org-fields='id,short_name'
                dest-fields='projectId,projectName'
                code='pm_project_select'
                @callback='popupCallback'
              />
              <input v-decorator="['projectId']" v-show='false'></input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['projectCode']" placeholder="系统自动带出" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="产品名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['productName',validatorRules.productName]" placeholder="请输入产品名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['productType',validatorRules.productType]" placeholder="请输入规格型号"/>
            </a-form-item>
          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-form-item label="单价" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <a-input v-decorator="['price',validatorRules.price]"-->
<!--                       placeholder="请输入单价"-->
<!--                       @input="changeInput"><span slot="addonAfter">元</span></a-input>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="12">
            <a-form-item label="数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['num',validatorRules.num]" placeholder="请输入数量"  @input="changeInput" ></a-input>
            </a-form-item>
          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-form-item label="总价" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <a-input v-decorator="['countPrice', {initialValue:0}]" placeholder="系统自动计算" style="width: 100%" type="number" precision="2" disabled >-->
<!--                <span slot="addonAfter">元</span>-->
<!--              </a-input>-->
<!--&lt;!&ndash;              <a-input v-decorator="['countPrice']" placeholder="系统自动计算" type="number" precision="2" disabled></a-input>&ndash;&gt;-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :span="12">-->
<!--            <a-form-item label="预算" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <a-input v-decorator="['budget',validatorRules.budget]" placeholder="请输入预算" precision="2" ><span slot="addonAfter">元</span></a-input>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :span="12">-->
<!--            <a-form-item label="采购人" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-select-user-by-dep :multi="false" v-decorator="['buyerName',validatorRules.buyerName]" placeholder="请选择采购人"></j-select-user-by-dep>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="12">
            <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['purchaseState',validatorRules.purchaseState]"
                                 :trigger-change="true" dictCode="purchases_state" placeholder="请选择状态" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="交付时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="交付时间" v-decorator="['deliveryTime', validatorRules.deliveryTime]" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-form-item label="采购时间" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-date placeholder="请选择采购时间" v-decorator="['purchaseTime', validatorRules.purchaseTime]" :trigger-change="true" style="width: 100%" />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="24">
            <a-form-item label="配置要求" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
              <a-textarea v-decorator="['configuration',validatorRules.configuration]" rows="4" placeholder="请输入配置要求" />
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <hf-project-select-modal ref="hfProjectSelectModal" :multiple="false" @hf-pm-project-select="hfPmProjectSelect"/>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import HfProjectSelectModal from '@views/hifar/pm/modules/HfProjectSelectModal'

  export default {
    name: 'HfPmProjectPurchasesForm',
    components: {
      HfProjectSelectModal
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 }
        },
        confirmLoading: false,
        validatorRules: {
          projectShortName: {
            rules: [
              { required: true, message: '请选择项目简称!' }
            ]
          },
          productType: {
            rules: [
              { required: true, message: '请输入规格型号!' }
            ]
          },
          price: {
            rules: [
              { required: true, message: '请输入单价!' },
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
            ]
          },
          num: {
            rules: [
              { required: true, message: '请输入数量!' },
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
            ]
          },
          countPrice: {
            rules: [
              { required: true, message: '请输入总价!' },
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
            ]
          },
          budget: {
            rules: [
              { required: false, message: '请输入总价!' },
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!' }
            ]
          },
          purchaseState: {
            rules: [
              { required: true, message: '请选择状态!' }
            ],
            initialValue:"0"
          },
          buyerName: {
             rules: [
               { required: true, message: '请选择采购人!' }
             ]
          },
          deliveryTime: {
            rules: [
              { required: true, message: '请选择交付时间!' }
            ]
          },
          purchaseTime: {
            rules: [
              { required: true, message: '请选择采购时间!' }
            ]
          },
          productName: {
            rules: [
              { required: true, message: '请输入产品名称!' }
            ]
          },
          configuration: {
            rules: [
              { required: true, message: '请输入配置要求!' }
            ]
          },
        },
        url: {
          add: "/pm/hfPmProjectPurchases/add",
          edit: "/pm/hfPmProjectPurchases/edit",
          queryById: "/pm/hfPmProjectPurchases/queryById"
        },
        storeData: new Map(),
        defaultModel: {}
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      add () {
        let defaultObj = {}
        let {
          selectedName,
          selectedKeys,
          selectedCode,
          selectedTreeType
        } = this.defaultModel
        if (selectedTreeType === 'project') {
          defaultObj = {projectName: selectedName, projectId: selectedKeys, projectCode: selectedCode}
        }
        this.edit(defaultObj);
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'remarks','purchaseCode','projectId','projectName','projectCode','charger','productName','productType','price',
            'num','countPrice','buyerName','budget','purchaseState','configuration','deliveryTime','purchaseTime'))
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'remarks','purchaseCode','projectId','projectName','projectCode','charger','productName','productType','price',
          'num','countPrice','buyerName','budget','purchaseState','configuration','deliveryTime','purchaseTime'))
      },
      projectShortNameClick() {
        this.$nextTick(() => {
          this.$refs.hfProjectSelectModal.title = '选择项目'
          this.$refs.hfProjectSelectModal.visible = true
        })
      },
      hfPmProjectSelect(data) {
        this.form.setFieldsValue({
          projectId: data.id,
          projectName: data.shortName,
          projectCode:data.code,
          charger: data.charger
        })
      },
      // changeInput(e) {
      //
      //   var formTable = this.form.getForm();
      //   //获取数量
      //   let num = formTable.getFieldValue('num');
      //   //获取单价
      //   let price = formTable.getFieldValue('price');
      //   if (num == null) {
      //     this.$message.error('数量为空，总价无法计算!');
      //   }
      //   if (price == null) {
      //     this.$message.error('单价为空，总价无法计算!');
      //   }
      //   let total = price * num;
      //   //获取表单中总价文本框重新赋值
      //   formTable.setFieldsValue({
      //     ['countPrice']: total
      //   })
      // }
    }
  }
</script>